/**
* @file list_link.h
* @brief 侵入式链表
*/
#ifndef TIANYU_COMMON_LIST_LINK_H_
#define TIANYU_COMMON_LIST_LINK_H_

#include "common_define.h"

namespace common
{
	template< typename T >
	class CListLink
	{
 	 public:
		CListLink( )
		{
			prev_node_ = NULL;
			next_node_ = NULL;
			parent_ = NULL;
		}

		CListLink( T* parent )
		{
			prev_node_ = NULL;
			next_node_ = NULL;
			parent_ = parent;
		}

		~CListLink( )
		{
			Unlink( );
		}

		T* parent( ) { return parent_; }	
		CListLink< T >* prev_node( ) { return prev_node_; }	
		CListLink< T >* next_node( ) { return next_node_; }

		//将本节点插入到node节点后面
		void LinkBefore( CListLink< T >& node )
		{
			Unlink( );
			next_node_ = &node;
			prev_node_ = node.prev_node_;
			if( NULL != prev_node_ )
			{
				prev_node_->next_node_ = this;
			}
			if( NULL != next_node_ )
			{
				next_node_->prev_node_ = this;
			}
		}


		//将本节点插入到node节点前面
		void LinkAfter( CListLink< T >& node )
		{
			Unlink( );
			prev_node_ = &node;
			next_node_ = node.next_node_;
			if( NULL != prev_node_ )
			{
				prev_node_->next_node_ = this;
			}
			if( NULL != next_node_ )
			{
				next_node_->prev_node_ = this;
			}
		}

		void Unlink( )
		{
			if( NULL != prev_node_ )
			{
				prev_node_->next_node_ = next_node_;
			}
			if( NULL != next_node_ )
			{
				next_node_->prev_node_ = prev_node_;
			}
			prev_node_ = NULL;
			next_node_ = NULL;
		}

	 private:
		CListLink< T >* prev_node_;
		CListLink< T >* next_node_;
		T* parent_;
	};
}


#endif

